/**
 * 系统人员页面
 */
var tmpl_query = '\
		<div class="pane-form" id="queryTable">\
				<ul>\
					<li><label>真实姓名：<input type="text" id="userName"><label>\
					</li>\
					<li><label>角色：<select id="userRole" >\
										</select><label>\
					</li>\
					<li><a class="btn btn-success btn-xs" id="querybt">查询</a></li>\
				</ul>\
		</div>';

var tmpl_list = '\
	<div class="uqe-pane pane-list">\
		<header class="header">\
			<label>用户列表</label>\
			<div class="toolbar right">\
				<a class="btn btn-success btn-xs glyphicon glyphicon-plus">添加用户</a>\
				<a class="btn btn-success btn-xs glyphicon glyphicon-edit">修改用户</a>\
				<a class="btn btn-success btn-xs glyphicon glyphicon-remove">删除用户</a>\
			</div>\
		</header>\
		<div class="body">\
			<table class="table">\
				<thead>\
					<tr>\
						<th><input type="checkbox" class ="row_checkbox" name="idAll" id="idAll"></th>\
						<th>序号</th>\
						<th>用户名</th>\
						<th>真实姓名</th>\
						<th>性别</th>\
						<th>角色</th>\
						<th>备注</th>\
					</tr>\
				</thead>\
				<tbody>\
				</tbody>\
			</table>\
		</div>\
	<footer class="footer"></footer>\
	</div>';

var tmpl_new = '\
	<div class="windowEdit uqe-pane">\
		<img src="../images/bt-close.png" class="edit_close">\
		<header class="header">\
			<label id="addUserLabel" >添加新用户</label>\
		</header>\
		<div class="body">\
			<form name="form2" method="post">\
        		<table class="infoTbl" >\
					<tr>\
						<td>\
						</td>\
						<td class="name">用户ID：</td>\
						<td>\
							<input class="user_input" type="text" id="realId_new">\
						</td>\
					</tr>\
					<tr>\
						<td>\
							<span class="must_input">* \
						</td>\
						<td class="name">真实姓名：</td>\
						<td>\
							<input class="user_input" type="text" id="realName_new">\
						</td>\
					</tr>\
					<tr>\
						<td>\
							<span class="must_input">* \
						</td>\
						<td class="name">性别：</td>\
						<td>\
							<select class="user_input" type="text" id="realSex_new">\
										<option value ="男" default >男</option>\
										<option value ="女">女</option>\
							</select>\
						</td>\
					</tr>\
					<tr>\
						<td>\
							<span class="must_input">* \
						</td>\
						<td class="name">密码：</td>\
						<td>\
							<input class="user_input" type="password" id="realPassword_new">\
						</td>\
					</tr>\
					<tr>\
						<td>\
							<span class="must_input">* \
						</td>\
						<td class="name">重复密码：</td>\
						<td>\
							<input class="user_input" type="password" id="realDPassword_new">\
						</td>\
					</tr>\
					<tr>\
						<td>\
							<span class="must_input">* \
						</td>\
						<td class="name">所属角色：</td>\
						<td>\
							<select class="user_input" type="text" id="realroleName_new">\
							</select>\
						</td>\
					</tr>\
					<tr>\
						<td>\
						</td>\
					</tr>\
				</table>\
			</form>\
		</div>\
		<footer class="footer" style="text-align: center;">\
				<a class="btn btn-success btn-xs glyphicon glyphicon-saved">保存并继续</a>\
				<a class="btn btn-success btn-xs glyphicon glyphicon-ok">确定</a>\
				<a class="btn btn-success btn-xs glyphicon glyphicon-trash">取消</a>\
		</footer>\
	</div>';

$(function() {
	var divQuery = $(tmpl_query).appendTo('body');
	var divList = $(tmpl_list).appendTo('body');
	var divNew = $(tmpl_new).appendTo('body');
	$('<div class="black_overlay">').appendTo('body');

	var pageSize = 10000;
	var pageNo = 1;
	
	$('#userRole').html("");
	var param = {};
	top.Proxy.generalPostAjax('role/query' , param ,  function(res) {
		 $('<option>').attr('value', '').html('所有角色').appendTo('#userRole');
			$(res.result).each(
					function(index, roleType) {
						$('<option>').attr('value', roleType.name  )
								.html(roleType.name).appendTo('#userRole');
					});
	}, function(e) {
			console.log( e )
		  alert("获取角色 出错");
	});
	
	 
	// 点击新增用户
	divList.find('.glyphicon-plus').click(
			function() {
				$('#realId_new').val('');
				$('#realName_new').val('');
				$('#realPassword_new').val('');
				$('#realDPassword_new').val('');
				$('#realDept_new').val('');
				$("#realId_new").removeAttr("disabled");
				$(".glyphicon-saved").show();
				$("#addUserLabel").html("添加新用户"); 
				
				$(".black_overlay").show();
				
				$("#realId_new").attr("disabled", "true");
				
				divNew.show();
				// 填充角色下拉框
				var param = {};
				$('#realroleName_new').html("");
				$('<option value="">').html("请选择").appendTo('#realroleName_new');
				top.Proxy.generalPostAjax('role/query' , param ,  function(res) {
					$(res.result).each(
							function(index, roleType) {
								$('<option>').attr('value', roleType.name  )
								.html(roleType.name).appendTo('#realroleName_new');
							});
				}, function() {
					alert("请求角色出错");
				});
			});

	// 修改用户
	divList.find('.glyphicon-edit').click(function() {
		var userId ="";
		var inx = 0;
		$('input:checkbox[name=ids]:checked').each(function(i) {
			inx++;
			userId  = $(this).val();
		});

		if (inx == 0) {
			alert('请选择要修改的用户');
			return;
		} else if (inx > 1) {
			alert('无法批量修改用户信息，请选择一位用户');
			return;
		}
		var param = {};
		$('#realroleName_new').html("");
		$('<option value="">').html("请选择").appendTo('#realroleName_new');
		top.Proxy.generalPostAjax('role/query' , param ,  function(res) {
			$(res.result).each(
					function(index, roleType) {
						$('<option>').attr('value', roleType.name  )
						.html(roleType.name).appendTo('#realroleName_new');
					});
		}, function() {
			alert("请求角色出错");
		});
		var params={
				 conditions:[],
				 relation: 'AND'  
		};
		params.conditions.push( { "name":"user_id", "logic":"="  ,"value":userId  });
		 
		
		top.Proxy.generalPostAjax('user/query' , params ,  function(res) {
			$(res.result).each(function(index, user) {
						 $('#realId_new').val(user.userId) ;
						 $('#realName_new').val(user.userName) ;
						 $('#realPassword_new').val(user.password) ;
						 $('#realDPassword_new').val(user.password) ;
						 $('#realroleName_new').val(user.roleName); 
					});
		}, function() {
			alert("查询用户出错");
		});
		divNew.show();
		$(".black_overlay").show();
		$("#realId_new").attr("disabled", "false");
		$(".glyphicon-saved").hide();
		$("#addUserLabel").html("修改用户信息");
	});
	
	// 删除用户
	divList.find('.glyphicon-remove').click(function() {
		var truthBeTold = window.confirm("确定要删除所选的用户吗？");
		if (!truthBeTold) {
			return;
		}
		var userIds ="";
		var inx = 0;
		
		
		
		var values = [];
		
		$('input:checkbox[name=ids]:checked').each(function(i) {
			inx++;
			userIds+= $(this).val()+"," ;
			values.push( $(this).val() );
		});
		if( userIds.length>1)
			userIds=userIds.substring(0,userIds.length-1);
	
		if( userIds.length==0){
			alert("请选择要删除的用户");
			return ;
		}
		
		var params={
				 conditions:[],
				 relation: 'AND'  
		};
		params.conditions.push( { "name":"user_id", "logic":"IN"  ,"values":values   });
		top.Proxy.generalPostAjax('user/remove' , params ,  function(res) {
			alert("删除用户成功,共删除了"+(res.result)+"个用户");
			__query();
		}, function(res) {
			alert(res.message);
		});
	});
	
	// 行复选框
	$("#idAll").click(function() {
		var b = this.checked;
		$("input[name='ids']").each(function() {
			$(this).attr("checked", b);
		});
	});

	divNew.find('.glyphicon-saved').click(function() {
			__addUser("2");
	});

	divNew.find('.glyphicon-ok').click(function() {
		if( $("#addUserLabel").html()=="修改用户信息"){
			__updateUser();
		}else if ($("#addUserLabel").html()=="添加新用户"){
			__addUser("1");
		}
	});

	divNew.find('.glyphicon-trash').click(function() {
		divNew.hide();
		$(".black_overlay").hide();
	});
	divNew.find('.edit_close').click(function() {
		divNew.hide();
		$(".black_overlay").hide();
	});

	//点击查询
	var tbody = divList.find('tbody');

	divQuery.find('.btn-success').click(function() {
		pageNo = 1;
		__query();
	});

	var __addUser = function(type) {
		var userName = $('#realName_new').val().trim();
		var password = $('#realPassword_new').val().trim();
		var dpassword = $('#realDPassword_new').val().trim();
		var roleName = $('#realroleName_new').val();
		var sex = $('#realSex_new').val();
		var description = $('#realDescription_new').val();
		 
		if (userName == null || userName == '') {
			alert("请填写用户真实姓名");
			return;
		}
		if (password == null || password == '') {
			alert("请填写用户密码");
			return;
		}
		if (password != dpassword) {
			alert("两次密码不一致");
			return;
		}
		if (roleName == null || roleName == '') {
			alert("请选择角色");
			return;
		}
		var param = {
			 
			userName : userName,
			password : password,
			sex:    sex,
			roleName : roleName ,
			description:description
		};
		 
		
		
		top.Proxy.generalPostAjax('user/add' , param ,  function(res) {
			alert("新建用户成功");
			if(type == '1'){
				divNew.hide();
				$(".black_overlay").hide();
			}
			$('#realId_new').val('');
			$('#realName_new').val('');
			$('#realPassword_new').val('');
			$('#realDPassword_new').val('');
			__query();
		}, function(e) {
			alert( e.message);
		});
	};
	var __updateUser = function() {
		var userId = $('#realId_new').val().trim();
		var userName = $('#realName_new').val().trim();
		var passWord = $('#realPassword_new').val().trim();
		var dpassword = $('#realDPassword_new').val().trim();
		var roleId = $('#realroleName_new').val();
		 
//		if (userId == null || userId == '') {
//			alert("请填写用户名");
//			return;
//		}
		if (userName == null || userName == '') {
			alert("请填写用户真实姓名");
			return;
		}
		if (passWord == null || passWord == '') {
			alert("请填写用户密码");
			return;
		}
		if (passWord != dpassword) {
			alert("两次密码不一致");
			return;
		}
		if (roleId == null || roleId == '') {
			alert("请选择角色");
			return;
		}
	 
		var param = {
			userId : userId,
			userName : userName,
			password : passWord,
			roleName : roleId 
		};
		
		
		top.Proxy.generalPostAjax('user/update' , param ,  function(res) {
			alert("修改用户成功");
			divNew.hide();
			$(".black_overlay").hide();
			$('#realId_new').val('');
			$('#realName_new').val('');
			$('#realPassword_new').val('');
			$('#realDPassword_new').val('');
			$('#realDept_new').val('');
			__query();
		}, function(e) {
			alert( e.message);
		});
		
		
//		top.Proxy.updateUser(param, function(res) {
//			alert("修改用户成功");
//			divNew.hide();
//			$(".black_overlay").hide();
//			$('#realId_new').val('');
//			$('#realName_new').val('');
//			$('#realPassword_new').val('');
//			$('#realDPassword_new').val('');
//			$('#realDept_new').val('');
//			__query();
//		}, function(res) {
//			alert(res.message);
//		});
	};
	var __query = function() {
		tbody.empty();
		$('#idAll').removeAttr("checked");
	 
		var userName = $('#userName').val().trim();
		var roleId = $('#userRole').val();

		var params={
				 conditions:[],
				 relation: 'AND' ,
				 start: (pageNo-1) * pageSize,
				 limit: pageSize
		};
		if(userName!=null && userName.trim().length>0)
		{
			params.conditions.push( { "name":"user_name", "logic":"like"  ,"value":"%"+userName+"%"  });
		}
		
		if(roleId!=null && roleId.trim().length>0)
		{
			params.conditions.push( { "name":"role_name", "logic":"="  ,"value":roleId   });
		}
		top.Proxy.generalPostAjax('user/page' , params ,  function(res) {
			var total = res.total;
			$(res.result).each(
					function(index, user) {
						var tr = $('<tr>').appendTo(tbody);
						var tdFirst = $('<td>').appendTo(tr);
						$('<input type="checkbox" name="ids">').attr('id',user.userId).attr('value', user.userId).click(function(){
							var indexNum = 0;
							$(':input[name="ids"]').each(function(){
								if(!this.checked){
									indexNum ++;
								}
							 });
							if(indexNum > 0){
								$('#idAll').removeAttr("checked");
							}else{
								$('#idAll').attr("checked","checked");
							}
							event.stopPropagation();
						}).appendTo(tdFirst);
						$('<td>').html(index + 1).appendTo(tr);
						$('<td>').html(user.userId).appendTo(tr);
						$('<td>').html(user.userName).appendTo(tr);
						$('<td>').html(user.sex).appendTo(tr);
						$('<td>').html(user.roleName).appendTo(tr);
						$('<td>').html(user.description).appendTo(tr);
						
						tr.hover(  
								  function() {$(this).addClass('highlight');},  
								  function() {$(this).removeClass('highlight');}  
								 );  
						
						tr.click(function() {
									$(this).siblings().removeClass('selected');  
									$(this).toggleClass('selected');
									var check = $(this).find(':checkbox');
									var value= check.attr('checked');
									check.attr('checked',!value);
									  
									var indexNum = 0;
									$(':input[name="ids"]').each(function(){
										if(!this.checked){
											indexNum ++;
										}
									 });
									if(indexNum > 0){
										$('#idAll').removeAttr("checked");
									}else{
										$('#idAll').attr("checked","checked");
									}
						});  
					});
			__updatePages(total);
			
			
		}, function(e) {
				console.log( e )
			  alert("获取本地工单 出错");
		});
		
		
//		top.Proxy.getUser4Page(params, function(res) {
//			var total = res.total;
//			$(res.result).each(
//					function(index, user) {
//						var tr = $('<tr>').appendTo(tbody);
//						var tdFirst = $('<td>').appendTo(tr);
//						$('<input type="checkbox" name="ids">').attr('id',user.userId).attr('value', user.userId).click(function(){
//							var indexNum = 0;
//							$(':input[name="ids"]').each(function(){
//								if(!this.checked){
//									indexNum ++;
//								}
//							 });
//							if(indexNum > 0){
//								$('#idAll').removeAttr("checked");
//							}else{
//								$('#idAll').attr("checked","checked");
//							}
//							event.stopPropagation();
//						}).appendTo(tdFirst);
//						$('<td>').html(index + 1).appendTo(tr);
//						$('<td>').html(user.userId).appendTo(tr);
//						$('<td>').html(user.userName).appendTo(tr);
//						$('<td>').html(user.roleId).appendTo(tr);
//						$('<td>').html(user.department).appendTo(tr);
//						
//						tr.hover(  
//								  function() {$(this).addClass('highlight');},  
//								  function() {$(this).removeClass('highlight');}  
//								 );  
//						
//						tr.click(function() {
//									$(this).siblings().removeClass('selected');  
//									$(this).toggleClass('selected');
//									var check = $(this).find(':checkbox');
//									var value= check.attr('checked');
//									check.attr('checked',!value);
//									  
//									var indexNum = 0;
//									$(':input[name="ids"]').each(function(){
//										if(!this.checked){
//											indexNum ++;
//										}
//									 });
//									if(indexNum > 0){
//										$('#idAll').removeAttr("checked");
//									}else{
//										$('#idAll').attr("checked","checked");
//									}
//						});  
//					});
//			__updatePages(total);
//		}, function() {
//			alert("查询用户出错");
//		});
	};

	var __updatePages = function(total) {
		var divPage = divList.find('footer');
		divPage.empty();
		var divPageSum = $('<div style="position: absolute;left: 0;color:#529F02;padding: 0.3em 0.5em;margin:0.3em;">').appendTo(divPage);
		var totalPage = parseInt(total / pageSize);
		if (totalPage == 0 || total % pageSize != 0) {
			totalPage ++;
		}
		divPageSum.html("<img src='../images/page-flower.png'>  页数" + pageNo + "/" + totalPage +' ， '+  "总记录数 " + total+"，每页显示：");
		var select = $('<select>').val(pageSize).appendTo(divPageSum);
		var sizeArray = [5,10,15,20,50,100];
		$(sizeArray).each(function(i,size){
			var sizeOption = $('<option>').html(size).val(size).appendTo(select);
			if(pageSize==size){
				sizeOption.attr('selected','selected');
			}
		});
		$(select).change(function(){
			pageSize = $(this).val();
			pageNo = 1;
			__query();
		});
		var divPageDetail = $('<div class="pageDetail">').appendTo(divPage);
		var ulPage = $('<ul class="pagination pagination-sm">').appendTo(divPageDetail);
		var pageData = [{
			Name:'首页',
			PageNum:1
		}];
		pageNo == 1 ? pageData.push({Name: '上一页', PageNum: 0}) : pageData.push({Name: '上一页', PageNum: pageNo-1});
		if(pageNo>4){
			for (var i = pageNo - 2; i <= (pageNo + 2> totalPage ? totalPage : pageNo + 2); i++) {
				pageData.push({Name : i,PageNum : i});
			}
		}else if(pageNo <= 4 && totalPage > 1){
			for(var j = 1; j <= ( totalPage >= 4 ? 4 : totalPage); j++){
				pageData.push({Name:j,PageNum:j});
			}
		}
		pageNo == totalPage ? pageData.push({Name: '下一页',PageNum : 0}) : pageData.push({Name: '下一页', PageNum: pageNo+1});
		pageData.push({Name: '尾页',PageNum: totalPage});
		$(pageData).each(function(index , page){
			var lipage = $('<li>').appendTo(ulPage);
			var apage = $('<a>').css('cursor','pointer').html(page.Name).appendTo(lipage);
			if(pageNo==page.Name){
				apage.css('color','#fff').css('background-color','#529F02');
			}
			if(page.PageNum > 0){
				apage.click(function(){
					__openPage(page.PageNum);
				});
			}
		});
	};
	
	var __openPage = function(pageno){
		divList.find('footer').empty();
		pageNo = pageno;
		__query();
	};

	//页面打开时主动查询一次
	__query();
	
	$("#queryTable").bind("keydown",function(e){
        // 兼容FF和IE和Opera    
    var theEvent = e || window.event;    
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;    
    if (code == 13) {    
        //回车执行查询
    		$('#querybt').click();
        }    
	});

});